<?php
/*
[
    {
        "total":3954884608,
        "used":1713172480,
        "free":200175616,
        "shared":340094976,
        "buffers":71774208,
        "cache":1969762304,
        "available":1699749888
    },
    {
        "total":3973050368,
        "used":773398528,
        "free":3199651840,
        "shared":0,
        "buffers":0,
        "cache":0,
        "available":0
    }
]
*/
function getOriginMemoryInfo(): array {
    $resource = popen('LANG=en free -bw 2>&1', 'rb');
    if (false === $resource) {
        return [];
    }
    $outputString = fread($resource, 4096);
    pclose($resource);
    $allLines = explode(PHP_EOL, $outputString);
    if (!isset($allLines[1])) {
        return [];
    }
    foreach ($allLines as &$line) {
        $line = explode(' ', $line);
        foreach ($line as $i => $char) {
            if ('' === $char) {
                unset($line[$i]);
            }
        }
        $line = array_values($line);
    }
    return $allLines;
}

function processFormate(array $origin): array {
    if (empty($origin)) {
        return [];
    }
    if (!isset($origin[0], $origin[1])) {
        return [];
    }
    $head = $origin[0];
    if (!isset($head[0], $head[1], $head[2], $head[3], $head[4], $head[5], $head[6])) {
        return [];
    }
    $formateArray = [];
    foreach ($origin as $i => $x) {
        if ($i == 0) {
            continue;
        }
        array_shift($origin[$i]);
        if (count($origin[$i]) < count($head)) {
            $origin[$i] = array_pad($origin[$i], count($head), '');
        }
        $formateArray[] = array_combine($head, array_map(function($v) {return is_numeric($v) ? intval($v) : 0;}, $origin[$i]));
    }
    return $formateArray;
}

function httpResponse(array $data): string {
    header('Content-Type: application/json');
    $httpText = json_encode($data);
    echo $httpText;
    return $httpText;
}

httpResponse(processFormate(getOriginMemoryInfo()));
